const express = require('express')
const app = express()

//跨域中间件
const cors = require('cors')
app.use(cors())

//解析application、x-www-form-urlencided格式数据
app.use(express.json())
app.use(express.urlencoded({ extended: false }))

//封装res.err函数用于后续简化代码
app.use((req, res, next) => {
    // 需要判断err错误信息是对象还是字符串
    res.cc = (err, status = 1) => {
        res.send({
            status,
            message: err instanceof Error ? err.message : err
        })
    }
    next()
})

//解析token的中间件
const jwt = require('express-jwt')
const jwtSecretKey = require('./config')
app.use(jwt({
        secret: jwtSecretKey.key,
        algorithms: ['HS256'], //编码加密方式
        //截取客户端发送给服务端的token
        getToken: req => {
            // console.log(req.headers.authorization);
            if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
                return req.headers.authorization.split(' ')[1];
            } else if (req.query && req.query.token) {
                return req.query.token;
            }
            return null;
        }
    }).unless({ path: ['/api/login', '/api/register', '/api/qiniuToken'] })) //除了这两个地址，其余都需要token认证

//引入路由模块
const router = require('./router/router')
app.use('/api', router)


// 错误中间件处理函数
app.use((err, req, res, next) => {
    //身份认证失败的错误
    if (err.name === 'UnauthorizedError') return res.cc("身份验证失败!")

    res.cc(err)
})

app.listen(80, () => {
    console.log("http://127.0.0.1");
})